import fs from 'node:fs'
import { dialog, ipcMain, shell } from 'electron'
import _ from 'lodash'
import { Handler } from '../constant/constant.js'
import { DiskFile } from '../entity/diskFile.js'
import FileFilter = Electron.FileFilter

// 文件类控制器
export function fileHandlerSetup() {
  console.debug('load fileHandlerSetup')

  /**
   * 打开文件夹，选择文件夹
   */
  ipcMain.handle(Handler.showOpenDialog, () => {
    const filePaths = dialog.showOpenDialogSync({
      properties: ['openDirectory', 'createDirectory'],
    })
    if (_.isEmpty(filePaths)) {
      return null
    }
    console.log(filePaths)
    return filePaths?.[0]
  })
  /**
   * 打开指定文件
   */
  ipcMain.handle(Handler.openPath, (event, filePath: string) => {
    shell.openPath(filePath).then((res) => {
      console.log(res)
    })
  })
  /**
   * 使用UTF-8编码读取指定文件，会返回string
   */
  ipcMain.handle(Handler.readFile, (event, filePath: string) => {
    const buffer = fs.readFileSync(filePath, {
      encoding: 'utf-8',
    })
    return buffer
  })

  /**
   * 选择文件
   */
  ipcMain.handle(
    Handler.selectFile,
    async (
      event,
      extension: FileFilter[] = [
        {
          name: '*',
          extensions: ['*'],
        },
      ],
    ) => {
      return dialog
        .showOpenDialog({
          properties: ['openFile'],
          filters: extension,
        })
        .then((result) => {
          if (result.canceled) {
          }
          else {
            return result.filePaths[0]
          }
        })
    },
  )

  /**
   * 获取指定文件夹内的文件与文件夹列表，不向内递归
   */
  ipcMain.handle(Handler.getFileList, (event, path) => {
    const fileList = fs.readdirSync(path, {
      encoding: 'utf-8',
      withFileTypes: true,
    })
    if (_.isEmpty(fileList)) {
      return null
    }
    const array: DiskFile[] = []
    fileList.forEach((file) => {
      const temp = new DiskFile()
      const folder = file.isDirectory()
      temp.folder = folder
      temp.name = file.name
      temp.icon = ''
      temp.iconPath = ''
      temp.parentPath = file.parentPath
      temp.suffix = folder ? '' : file.name.split('.').pop()
      array.push(temp)
      try {
        const stat = fs.statSync(`${file.parentPath}/${file.name}`, {
          bigint: true,
        })
        temp.ino = stat.ino
        temp.size = stat.size
        temp.ctime = stat.ctime.toLocaleDateString()
        temp.atime = stat.atime.toLocaleDateString()
        temp.birthtime = stat.birthtime.toLocaleDateString()
      }
      catch (e) {
        console.log('file stat failed', file.name, e)
      }
    })
    return array
  })
}
